package com.ruoyi.web.core.config;



import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.spring.SpringUtils;

import com.ruoyi.framework.web.service.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;


import javax.annotation.PostConstruct;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import java.util.List;
import java.util.Map;
@Slf4j
@Configuration
public class WebsocketConfig  extends ServerEndpointConfig.Configurator  {


  private static TokenService tokenService;
  @Autowired(required = false)
  private ToService toService;



    public WebsocketConfig(){
        super();
        log.info("WebsocketConfig");
    }

    /**
     * 修改握手,就是在握手协议建立之前修改其中携带的内容
     * @param sec
     * @param request
     * @param response
     */
    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {

        Map<String, Object> userProperties = sec.getUserProperties();
        Map<String, List<String>> headers = request.getHeaders();
        List<String> authorization = headers.get("Sec-WebSocket-Protocol");

        if (!CollectionUtils.isEmpty(authorization)) {
            String x=authorization.get(0);

           // RedisService redisService = new RedisService();
            TokenService tokenService = SpringUtils.getBean(TokenService.class);

            LoginUser user = tokenService.getLoginUserByToken(x);

            userProperties.put("user", user);

        }
        response.getHeaders().put("Sec-WebSocket-Protocol",authorization);
    }


    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        //这个对象说一下，貌似只有服务器是tomcat的时候才需要配置,具体我没有研究
        return new ServerEndpointExporter();
    }
    @Autowired
    public void setxx(TokenService tokenService){
        WebsocketConfig.tokenService =tokenService;
    }





}
